package com.zhiwang.planet.aop.util

import android.annotation.SuppressLint
import android.view.View
import com.zhiwang.planet.util.androidSchedule
import io.reactivex.Flowable
import io.reactivex.Observable
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.Signature
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.reflect.MethodSignature
import java.util.concurrent.TimeUnit


@Target(AnnotationTarget.FUNCTION)
annotation class Throttle(val time: Int = 2)


val sThrottleMethodCache = hashSetOf<Signature>()

@Aspect
class ViewThrottleAspect {


    @SuppressLint("CheckResult")
    @Around("execution(@com.zhiwang.planet.aop.util.Throttle  * *(..))")
    fun throttleView(jp: ProceedingJoinPoint) {

        val sig = jp.signature

        var delay = 2

        if (sThrottleMethodCache.contains(sig))
            return

        sThrottleMethodCache.add(sig)

        if (sig is MethodSignature) {
            val throttle = sig.method.getAnnotation(Throttle::class.java)
            delay = throttle.time
        }


        jp.proceed()

        Observable.just(1)
                .delay(delay.toLong(), TimeUnit.SECONDS)
                .androidSchedule()
                .subscribe({
                    sThrottleMethodCache.remove(sig)
                }, {
                    sThrottleMethodCache.remove(sig)
                })
    }

}